package com.xms.plugin.service;

import com.xms.core.enums.OperationStage;
import com.xms.core.enums.OperationType;
import com.xms.plugin.core.FormPluginExecutionContext;
import com.xms.plugin.core.IFormPlugin;
import com.xms.plugin.core.PluginType;
import com.xms.plugin.entity.EntityPlugin;
import com.xms.security.identity.ICurrentUser;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 * FormPluginExecutor
 * </p>
 *
 * @author migo
 * @since 2021/10/15
 */
@Service
public class FormPluginExecutor<TData, KMetadata> implements IFormPluginExecutor<TData, KMetadata> {
    private IEntityPluginFinderService _entityPluginFinderService;
    private IEntityPluginFileProvider _entityPluginFileProvider;
    private ICurrentUser _currentUser;
    @Autowired
    public FormPluginExecutor(ICurrentUser currentUser
            , IEntityPluginFinderService entityPluginFinderService
            , com.xms.plugin.service.IEntityPluginFileProvider entityPluginFileProvider)
    {
        _currentUser = currentUser;
        _entityPluginFinderService = entityPluginFinderService;
        _entityPluginFileProvider = entityPluginFileProvider;
    }

    @Override
    public void execute(UUID entityId, UUID businessObjectId, OperationType op, OperationStage stage, TData tData, KMetadata kMetadata) {
        List<EntityPlugin> plugins = _entityPluginFinderService.getByObjectId(entityId, businessObjectId, op.value(), PluginType.Form.value());
        if (CollectionUtil.notEmpty(plugins))
        {
            for (EntityPlugin pg : plugins)
            {
                if (!pg.getStatecode())
                {
                    continue;
                }
                IFormPlugin pinstance = getInstance(pg);
                if (pinstance != null)
                {
                    FormPluginExecutionContext<TData, KMetadata> context = new FormPluginExecutionContext<>();
                    context.messageName = op;
                    context.stage = stage;
                    context.target = tData;
                    context.user = _currentUser.getUser();
                    context.metadata = kMetadata;
                    pinstance.execute(context);
                }
            }
        }
    }

    private IFormPlugin<TData, KMetadata> getInstance(EntityPlugin entity)
    {
        IFormPlugin<TData, KMetadata> _instance = null;
        if (_entityPluginFileProvider.loadAssembly(entity))
        {
            //_instance = (IPlugin<TData, KMetadata>)_serviceResolver.ResolveUnregistered(Type.GetType(entity.ClassName, false, true));
        }
        return _instance;
    }
}
